// pages/weather/index.js
import {request} from "../../request/request.js"
Page({

  data: {
    la_lo: "",
    city: "",
    qcity: "",
    locationInfo: '',
    weather_type: '',
    current_weather: {},
    weatherList: [],
    animationData: {}
  },
  timeId: -1,
  onLoad: function (options) {
   
  },

  onShow: function () {
    // 经纬度信息
    const la_lo = wx.getStorageSync('la_lo').data || ''
    const time = wx.getSystemInfoSync('la_lo'.time)||''
    const location = wx.getStorageSync('location')||''
    if(!la_lo){
      // 缓存中不存在经纬度信息
      this.getLocation()
    }else{
      // 经纬度过期时间
      if(Date.now() - time > 1000 * 60 * 60 * 24){
        this.getLocation()
      }
      console.log('过期时间未到，使用本地经纬度信息');
      this.setData({la_lo, city: location.ad_info.district, locationInfo: location.ad_info.city + location.ad_info.district})
    }
    //读取本地缓存的本地天气数据 
    const local_weather = wx.getStorageSync('local_weather')||''
    if(!local_weather){
      const city = this.data.city
      this.getWeather(city)
    }else{
      //过期时间1h
      if(Date.now() - local_weather.time > 1000 * 3600){
        const city = this.data.city
        this.getWeather(city)
      }else{
        console.log('过期时间未到，使用本地数据');
        const data = local_weather.data
        const type = data.realtime.info
        const weather_type = {"晴": "icon-qing", "阴": "icon-yin", "雪": "icon-xue", "雾": "icon-wu", "雨": "icon-yu-", "云": "icon-yun", "多云": "icon-yun"}
        let current_weather ={}
        current_weather.type = data.realtime.info
        current_weather.wendu = data.realtime.temperature 
        current_weather.shidu = '空气湿度  ' + data.realtime.humidity //湿度
        current_weather.air = '空气质量指数  ' + data.realtime.aqi // 空气质量
        current_weather.low_high ='气温  ' + data.future[0].temperature
        current_weather.wind = data.realtime.direct + '  ~风力' + data.realtime.power //风力风向
        this.setData({current_weather, weatherList: data.future.slice(1,5), weather_type: weather_type[type]})
      }
    }

  },
  // 获取经纬度信息和具体位置信息
  getLocation: function(){
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        const la_lo = res.latitude + ',' + res.longitude;
        wx.setStorageSync('la_lo', {time: Date.now() ,data: la_lo})
        this.setData({la_lo})

        //同步等待获取具体位置信息
        const query_location_data ={
          location: la_lo,
          key: '6YIBZ-AVSRU-OBPVK-436LY-2UGRJ-PXBFG' //腾讯位置服务key
        }
        const url = 'https://apis.map.qq.com/ws/geocoder/v1/'
        //由经纬度获取具体位置信息，请求腾讯位置服务；
        request({url, data: query_location_data}).then(res => {
          // 存储用户位置信息到缓存
          wx.setStorageSync('location', res.data.result)
          const city = res.data.result.ad_info.district
          const locationInfo = res.data.result.ad_info.city + res.data.result.ad_info.district
          this.setData({city, locationInfo})

          //同步等待，获取一次本地天气信息
          this.getWeather(city)
        })
      }
    })

  },

   //查询天气信息
   getWeather: function(city){
    // 使用聚合数据接口，调用次数为100次
    const qcity = city.replace(/[区,县,市,省]/, '')
    const key = 'c63d063ffeb1f0a5bf84a4c8e298e717'
    const url = `https://apis.juhe.cn/simpleWeather/query?city=${qcity}&key=${key}`;
    request({url}).then(
      (res) => {
        console.log(res);
        //输入错误城市查询，友好提示
        if(res.data.error_code === 0){
          // 查询成功，查询城市返回渲染
          if(this.data.city===city){
            this.setData({qcity: ''})
          }else{
            this.setData({qcity: city})
          }
          const type = res.data.result.realtime.info
          const weather_type = {"晴": "icon-qing", "阴": "icon-yin", "雪": "icon-xue", "雾": "icon-wu", "雨": "icon-yu-", "云": "icon-yun", "多云": "icon-yun"}
          let current_weather ={}
          current_weather.type = res.data.result.realtime.info
          current_weather.wendu = res.data.result.realtime.temperature 
          current_weather.shidu = '空气湿度  ' + res.data.result.realtime.humidity //湿度
          current_weather.air = '空气质量指数  ' + res.data.result.realtime.aqi // 空气质量
          current_weather.low_high ='气温  ' + res.data.result.future[0].temperature
          current_weather.wind = res.data.result.realtime.direct + '  ~风力' + res.data.result.realtime.power //风力风向
          this.setData({current_weather, weatherList: res.data.result.future.slice(1,5), weather_type: weather_type[type]})
          //用户本地查询信息存入缓存
          if(city===this.data.city){
            wx.setStorageSync('local_weather', {time: Date.now(),data: res.data.result})
          }
        }else{
          wx.showToast({
            title: '输入正确地区名称',
            mask: true,
            icon: 'error'
          })
        }
      }
    )
  },

  //点击热点城市回调函数
  handleHotCity(e){
    const {city} = e.currentTarget.dataset
    if(this.data.qcity===city){
      return
    }else{
      this.getWeather(city)
    }
    
  },
  //输入框输入回调函数
  input_city: '',
  handleKeyInput(e){
    const {value} = e.detail
    if(!value.trim()){
      clearTimeout(this.timeId)
      this.input_city = ''
    }else{
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.input_city = value
      }, 300);
    }
  },
  //点击搜索按钮回调函数
  handleSearch(){
    const city = this.input_city
    if(!city.trim()){
      wx.showToast({
        title: '输入要查询城市',
        mask: true
      })
      return
    }else{
      this.getWeather(city)
    }
  },
  //刷新定位信息
  handleRefreshLocation(){
    let animation = wx.createAnimation({
      duration: 2500,
      timingFunction: 'ease'
    })
    animation.rotateZ(-720).step()
    this.setData({animationData: animation.export()})
    // 重置旋转角度，回归起点
    setTimeout(() => {
      animation.rotateZ(720).step()
      this.setData({animationData: animation.export()})
    }, 1000)
    this.getLocation()
    this.setData({qcity: ''})
  },

    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 重新分享方法
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    return {
      title: "天气查询",
      path: "/pages/weather/index"
    }
  },
  /**
   * 用户点击分享朋友圈
   */
  onShareTimeline(){}


})
